import * as THREE from 'three';
import { PhysicsWorld } from '../utils/PhysicsWorld';
import { Debug } from '../utils/Debug';

// 能量补给类型
export type PowerUpType = 'health' | 'energy' | 'speed' | 'firepower';

export class PowerUp {
  // Three.js相关
  private scene: THREE.Scene;
  private mesh: THREE.Group;
  private light: THREE.PointLight;
  
  // 位置和状态
  private position: THREE.Vector3;
  private active: boolean = true;
  private lifetime: number = 20; // 20秒后消失
  
  // 物理和碰撞
  private physics: PhysicsWorld;
  private collider: any;
  
  // 动画属性
  private rotationSpeed: number = 1.0;
  private bounceHeight: number = 0.3;
  private bounceSpeed: number = 2.0;
  private initialY: number;
  
  // 补给属性
  private type: PowerUpType;
  private amount: number;
  
  // 收集回调
  private onCollect: () => void;
  
  constructor(
    scene: THREE.Scene, 
    physics: PhysicsWorld,
    loadingManager: THREE.LoadingManager, 
    position: THREE.Vector3, 
    onCollect: () => void,
    type?: PowerUpType,
    amount?: number
  ) {
    this.scene = scene;
    this.physics = physics;
    
    // 确保position是一个有效的THREE.Vector3对象
    if (!(position instanceof THREE.Vector3)) {
      Debug.error('能量补给初始位置必须是THREE.Vector3类型');
      position = new THREE.Vector3(0, 0.5, 0);
    }
    
    this.position = position.clone();
    this.initialY = position.y;
    this.onCollect = onCollect;
    
    // 随机选择类型（如果未指定）
    if (!type) {
      const types: PowerUpType[] = ['health', 'energy', 'speed', 'firepower'];
      this.type = types[Math.floor(Math.random() * types.length)];
    } else {
      this.type = type;
    }
    
    // 根据类型设置默认数量（如果未指定）
    if (amount === undefined) {
      switch (this.type) {
        case 'health':
          this.amount = 25; // 恢复25点生命值
          break;
        case 'energy':
          this.amount = 50; // 恢复50点能量
          break;
        case 'speed':
          this.amount = 5; // 5秒速度提升
          break;
        case 'firepower':
          this.amount = 5; // 5秒火力提升
          break;
      }
    } else {
      this.amount = amount;
    }
    
    try {
      // 创建能量补给模型
      this.mesh = this.createMesh();
      this.mesh.position.copy(this.position);
      this.scene.add(this.mesh);
      
      // 添加光源
      this.light = new THREE.PointLight(this.getColorForType(), 1, 3);
      this.light.position.copy(this.position);
      this.scene.add(this.light);
      
      // 添加物理碰撞体
      this.collider = this.physics.addCollider(
        this.mesh,
        new THREE.Vector3(1, 1, 1), // 碰撞体尺寸
        this.position,
        0,
        'powerup'
      );
      
      Debug.log(`能量补给已创建, 类型: ${this.type}, 位置: (${position.x.toFixed(1)}, ${position.y.toFixed(1)}, ${position.z.toFixed(1)})`);
    } catch (error) {
      Debug.error(`创建能量补给时出错: ${error}`);
      throw error;
    }
  }
  
  private getColorForType(): number {
    switch (this.type) {
      case 'health':
        return 0x00ff00; // 绿色
      case 'energy':
        return 0x00aaff; // 蓝色
      case 'speed':
        return 0xffcc00; // 黄色
      case 'firepower':
        return 0xff4400; // 红色
      default:
        return 0x00aaff;
    }
  }
  
  private createMesh(): THREE.Group {
    const group = new THREE.Group();
    
    // 根据类型决定颜色
    const color = this.getColorForType();
    const emissiveColor = new THREE.Color(color).multiplyScalar(0.7).getHex();
    
    // 核心（发光球体）
    const coreGeometry = new THREE.SphereGeometry(0.3, 16, 16);
    const coreMaterial = new THREE.MeshStandardMaterial({
      color: color,
      emissive: emissiveColor,
      metalness: 0.3,
      roughness: 0.2,
      transparent: true,
      opacity: 0.8
    });
    
    const core = new THREE.Mesh(coreGeometry, coreMaterial);
    group.add(core);
    
    // 外环1
    const ring1Geometry = new THREE.TorusGeometry(0.5, 0.05, 8, 24);
    const ring1Material = new THREE.MeshStandardMaterial({
      color: color,
      emissive: emissiveColor,
      metalness: 0.5,
      roughness: 0.2
    });
    
    const ring1 = new THREE.Mesh(ring1Geometry, ring1Material);
    ring1.rotation.x = Math.PI / 2;
    group.add(ring1);
    
    // 外环2
    const ring2 = new THREE.Mesh(ring1Geometry, ring1Material);
    ring2.rotation.x = Math.PI / 4;
    ring2.rotation.y = Math.PI / 4;
    group.add(ring2);
    
    // 添加一个点光源
    const pointLight = new THREE.PointLight(color, 0.5, 1);
    pointLight.position.set(0, 0, 0);
    group.add(pointLight);
    
    return group;
  }
  
  /**
   * 检查能量补给是否处于活跃状态
   * @returns 返回能量补给的活跃状态
   */
  public isActive(): boolean {
    return this.active;
  }
  
  /**
   * 获取能量补给的类型
   * @returns 返回能量补给的类型
   */
  public getType(): PowerUpType {
    return this.type;
  }
  
  /**
   * 获取能量补给的数量
   * @returns 返回能量补给的数量
   */
  public getAmount(): number {
    return this.amount;
  }
  
  public update(deltaTime: number): boolean {
    if (!this.active) return false;
    
    // 更新生命周期
    this.lifetime -= deltaTime;
    if (this.lifetime <= 0) {
      this.dispose();
      return false;
    }
    
    // 淡入淡出效果（最后3秒）
    if (this.lifetime < 3) {
      const fade = this.lifetime / 3;
      this.mesh.traverse((child) => {
        if (child instanceof THREE.Mesh) {
          const material = child.material as THREE.MeshStandardMaterial;
          material.opacity = fade * 0.8; // 保持最大不透明度
        }
      });
      
      this.light.intensity = fade;
    }
    
    // 旋转动画
    this.mesh.rotation.y += this.rotationSpeed * deltaTime;
    
    // 上下浮动动画
    const bounceOffset = Math.sin(performance.now() / 1000 * this.bounceSpeed) * this.bounceHeight;
    this.mesh.position.y = this.initialY + bounceOffset;
    this.light.position.y = this.initialY + bounceOffset;
    
    // 更新物理碰撞体
    this.physics.updateCollider(
      this.collider,
      new THREE.Vector3(this.position.x, this.initialY + bounceOffset, this.position.z),
      0
    );
    
    // 检查与玩家碰撞
    this.checkCollision();
    
    return true;
  }
  
  private checkCollision(): void {
    // 检查是否与玩家碰撞
    const collisionRadius = 1.5; // 提供更大的收集半径以提高游戏性能
    
    if (this.physics.checkCollision(this.position, collisionRadius, 'player')) {
      this.collect();
    }
  }
  
  private collect(): void {
    // 播放收集动画
    this.playCollectAnimation();
    
    // 触发回调
    this.onCollect();
    
    // 停用碰撞
    this.active = false;
    
    Debug.log('能量补给已被收集');
  }
  
  private playCollectAnimation(): void {
    // 缩放动画
    const scale = { value: 1 };
    const startTime = performance.now();
    const duration = 300; // 毫秒
    
    const animate = () => {
      const elapsedTime = performance.now() - startTime;
      const progress = Math.min(elapsedTime / duration, 1);
      
      // 缩放并淡出
      const newScale = 1 + progress;
      this.mesh.scale.set(newScale, newScale, newScale);
      
      this.mesh.traverse((child) => {
        if (child instanceof THREE.Mesh) {
          const material = child.material as THREE.MeshStandardMaterial;
          material.opacity = 1 - progress;
        }
      });
      
      this.light.intensity = 1 - progress;
      
      if (progress < 1) {
        requestAnimationFrame(animate);
      } else {
        this.dispose();
      }
    };
    
    requestAnimationFrame(animate);
  }
  
  public dispose(): void {
    // 从场景中移除
    this.scene.remove(this.mesh);
    this.scene.remove(this.light);
    
    // 移除物理碰撞体
    this.physics.removeCollider(this.collider);
    
    this.active = false;
    
    Debug.log('能量补给资源已清理');
  }
}